<template>
  <div class="dashboard-page">
    <!-- 欢迎区域 -->
    <div class="welcome-section">
      <div class="welcome-content">
        <h2>欢迎回来，{{ userStore.userInfo?.realName }}！</h2>
        <p>今天是 {{ formatDate(new Date(), 'YYYY年MM月DD日 dddd') }}</p>
      </div>
      <div class="weather-info">
        <el-icon><Sunny /></el-icon>
        <span>晴天 25°C</span>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-section">
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-icon cases">
            <el-icon><Folder /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ dashboardStats.totalCases }}</div>
            <div class="stat-label">总案件数</div>
            <div class="stat-change">
              <span class="change-text">较昨日 +{{ dashboardStats.casesChange }}</span>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-icon contracts">
            <el-icon><Document /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ dashboardStats.totalContracts }}</div>
            <div class="stat-label">总合同数</div>
            <div class="stat-change">
              <span class="change-text">较昨日 +{{ dashboardStats.contractsChange }}</span>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-icon clients">
            <el-icon><User /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ dashboardStats.totalClients }}</div>
            <div class="stat-label">总客户数</div>
            <div class="stat-change">
              <span class="change-text">较昨日 +{{ dashboardStats.clientsChange }}</span>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-icon revenue">
            <el-icon><Money /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ formatMoney(dashboardStats.totalRevenue) }}</div>
            <div class="stat-label">总收入</div>
            <div class="stat-change">
              <span class="change-text">较昨日 +{{ formatMoney(dashboardStats.revenueChange) }}</span>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="16">
        <!-- 图表区域 -->
        <div class="card">
          <div class="card-header">
            <h3>案件趋势</h3>
            <el-radio-group v-model="chartPeriod" @change="updateChart">
              <el-radio-button label="week">最近一周</el-radio-button>
              <el-radio-button label="month">最近一月</el-radio-button>
              <el-radio-button label="year">最近一年</el-radio-button>
            </el-radio-group>
          </div>
          <div ref="chartRef" style="height: 300px;"></div>
        </div>

        <!-- 最近案件 -->
        <div class="card">
          <div class="card-header">
            <h3>最近案件</h3>
            <el-button type="link" @click="$router.push('/cases')">查看全部</el-button>
          </div>
          <el-table :data="recentCases" stripe>
            <el-table-column prop="caseNumber" label="案件编号" width="140" />
            <el-table-column prop="title" label="案件标题" show-overflow-tooltip />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusTagType(row.status)">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="clientName" label="客户" width="120" />
            <el-table-column prop="createdAt" label="创建时间" width="160">
              <template #default="{ row }">
                {{ formatDate(row.createdAt) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>

      <el-col :span="8">
        <!-- 待办事项 -->
        <div class="card">
          <div class="card-header">
            <h3>待办事项</h3>
            <el-button type="link" @click="handleAddTodo">添加</el-button>
          </div>
          <div class="todo-list">
            <div
              v-for="todo in todoList"
              :key="todo.id"
              class="todo-item"
              :class="{ completed: todo.completed }"
            >
              <el-checkbox
                v-model="todo.completed"
                @change="handleTodoChange(todo)"
              />
              <span class="todo-text">{{ todo.text }}</span>
              <el-button
                type="link"
                size="small"
                @click="handleDeleteTodo(todo)"
                class="delete-btn"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
        </div>

        <!-- 云法务核心功能 -->
        <div class="card">
          <h3>云法务核心功能</h3>
          <div class="cloud-legal-features">
            <div class="feature-grid">
              <div class="feature-card" @click="handleFeatureClick('ai-consultation')">
                <el-icon class="feature-icon"><ChatDotRound /></el-icon>
                <h4>智能咨询</h4>
                <p>AI法律问答，快速获得专业解答</p>
                <span class="feature-status">已上线</span>
              </div>
              <div class="feature-card" @click="handleFeatureClick('document-drafting')">
                <el-icon class="feature-icon"><EditPen /></el-icon>
                <h4>智能文书</h4>
                <p>文书起草、合同审查一键完成</p>
                <span class="feature-status">已上线</span>
              </div>
              <div class="feature-card" @click="handleFeatureClick('legal-search')">
                <el-icon class="feature-icon"><Search /></el-icon>
                <h4>法律检索</h4>
                <p>司法案例、法律法规快速检索</p>
                <span class="feature-status developing">开发中</span>
              </div>
              <div class="feature-card" @click="handleFeatureClick('enterprise-info')">
                <el-icon class="feature-icon"><OfficeBuilding /></el-icon>
                <h4>企业信息</h4>
                <p>企业查询、风险监测、尽调报告</p>
                <span class="feature-status">已上线</span>
              </div>
              <div class="feature-card" @click="handleFeatureClick('legal-calculator')">
                <el-icon class="feature-icon"><Calculator /></el-icon>
                <h4>法律计算器</h4>
                <p>律师费、诉讼费、利息计算</p>
                <span class="feature-status">已上线</span>
              </div>
              <div class="feature-card" @click="handleFeatureClick('legal-services')">
                <el-icon class="feature-icon"><Service /></el-icon>
                <h4>法务服务</h4>
                <p>专业律师团队一站式服务</p>
                <span class="feature-status planning">待设计</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 快捷操作 -->
        <div class="card">
          <h3>快捷操作</h3>
          <div class="quick-actions">
            <el-button type="primary" @click="$router.push('/cases')" class="action-btn">
              <el-icon><Plus /></el-icon>
              新增案件
            </el-button>
            <el-button type="success" @click="$router.push('/contracts')" class="action-btn">
              <el-icon><Document /></el-icon>
              新增合同
            </el-button>
            <el-button type="warning" @click="$router.push('/clients')" class="action-btn">
              <el-icon><User /></el-icon>
              新增客户
            </el-button>
            <el-button type="info" @click="$router.push('/documents')" class="action-btn">
              <el-icon><Upload /></el-icon>
              上传文档
            </el-button>
          </div>
        </div>

        <!-- 系统通知 -->
        <div class="card">
          <div class="card-header">
            <h3>系统通知</h3>
            <el-button type="text">查看全部</el-button>
          </div>
          <div class="notification-list">
            <div
              v-for="notification in notifications"
              :key="notification.id"
              class="notification-item"
            >
              <div class="notification-icon">
                <el-icon><Bell /></el-icon>
              </div>
              <div class="notification-content">
                <div class="notification-title">{{ notification.title }}</div>
                <div class="notification-time">{{ formatDate(notification.createdAt, 'MM-DD HH:mm') }}</div>
              </div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { useUserStore } from '@/stores/user'
import { formatDate, formatMoney } from '@/utils'
import { getCaseList } from '@/api/case'
import type { Case } from '@/types'

const userStore = useUserStore()
const chartRef = ref<HTMLElement>()
const chartPeriod = ref('month')
const recentCases = ref<Case[]>([])

const dashboardStats = reactive({
  totalCases: 156,
  casesChange: 12,
  totalContracts: 89,
  contractsChange: 5,
  totalClients: 234,
  clientsChange: 8,
  totalRevenue: 1250000,
  revenueChange: 85000
})

const todoList = ref([
  { id: 1, text: '审核张三的合同', completed: false },
  { id: 2, text: '准备明天的庭审材料', completed: false },
  { id: 3, text: '回复李四的法律咨询', completed: true },
  { id: 4, text: '整理本月财务报表', completed: false }
])

const notifications = ref([
  { id: 1, title: '案件 #2023001 状态已更新', createdAt: new Date() },
  { id: 2, title: '合同 #CT2023001 即将到期', createdAt: new Date(Date.now() - 3600000) },
  { id: 3, title: '新客户王五已注册', createdAt: new Date(Date.now() - 7200000) },
  { id: 4, title: '系统将于今晚进行维护', createdAt: new Date(Date.now() - 86400000) }
])

// 获取最近案件
const fetchRecentCases = async () => {
  try {
    const data = await getCaseList({ page: 1, size: 5 })
    recentCases.value = data.list
  } catch (error) {
    console.error('获取最近案件失败:', error)
  }
}

// 初始化图表
const initChart = async () => {
  await nextTick()
  if (chartRef.value) {
    const chart = echarts.init(chartRef.value)
    updateChart()
  }
}

// 更新图表
const updateChart = () => {
  if (!chartRef.value) return
  
  const chart = echarts.getInstanceByDom(chartRef.value)
  if (!chart) return
  
  const data = generateChartData(chartPeriod.value)
  
  chart.setOption({
    tooltip: { trigger: 'axis' },
    legend: { data: ['新增案件', '完成案件'] },
    xAxis: { type: 'category', data: data.categories },
    yAxis: { type: 'value' },
    series: [
      {
        name: '新增案件',
        type: 'bar',
        data: data.newCases,
        itemStyle: { color: '#409eff' }
      },
      {
        name: '完成案件',
        type: 'bar',
        data: data.completedCases,
        itemStyle: { color: '#67c23a' }
      }
    ]
  })
}

// 生成图表数据
const generateChartData = (period: string) => {
  const data = {
    categories: [] as string[],
    newCases: [] as number[],
    completedCases: [] as number[]
  }
  
  if (period === 'week') {
    data.categories = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    data.newCases = [12, 8, 15, 10, 18, 6, 9]
    data.completedCases = [8, 12, 10, 15, 12, 8, 11]
  } else if (period === 'month') {
    for (let i = 1; i <= 30; i++) {
      data.categories.push(`${i}日`)
      data.newCases.push(Math.floor(Math.random() * 20) + 5)
      data.completedCases.push(Math.floor(Math.random() * 15) + 3)
    }
  } else {
    data.categories = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    data.newCases = [45, 52, 38, 67, 73, 89, 94, 87, 76, 82, 91, 105]
    data.completedCases = [38, 47, 42, 59, 68, 81, 87, 79, 71, 75, 84, 98]
  }
  
  return data
}

// 添加待办事项
const handleAddTodo = () => {
  ElMessage.info('添加待办事项功能开发中')
}

// 待办事项状态变化
const handleTodoChange = (todo: any) => {
  ElMessage.success(todo.completed ? '任务已完成' : '任务已重新激活')
}

// 删除待办事项
const handleDeleteTodo = (todo: any) => {
  const index = todoList.value.findIndex(item => item.id === todo.id)
  if (index > -1) {
    todoList.value.splice(index, 1)
    ElMessage.success('待办事项已删除')
  }
}

// 处理云法务功能点击
const handleFeatureClick = (feature: string) => {
  switch (feature) {
    case 'ai-consultation':
      ElMessage.info('智能咨询功能：AI法律问答，快速获得专业解答')
      break
    case 'document-drafting':
      ElMessage.info('智能文书功能：文书起草、合同审查一键完成')
      break
    case 'legal-search':
      ElMessage.warning('法律检索功能正在开发中，敬请期待')
      break
    case 'enterprise-info':
      ElMessage.info('企业信息功能：企业查询、风险监测、尽调报告')
      break
    case 'legal-calculator':
      ElMessage.info('法律计算器功能：律师费、诉讼费、利息计算')
      break
    case 'legal-services':
      ElMessage.warning('法务服务功能待设计，将提供专业律师团队一站式服务')
      break
    default:
      ElMessage.info('功能开发中...')
  }
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    pending: 'warning',
    processing: 'primary',
    completed: 'success',
    closed: 'info'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    pending: '待处理',
    processing: '处理中',
    completed: '已完成',
    closed: '已关闭'
  }
  return textMap[status] || status
}

onMounted(() => {
  fetchRecentCases()
  initChart()
})
</script>

<style lang="scss" scoped>
.dashboard-page {
  .welcome-section {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #fff;
    padding: 30px;
    border-radius: 12px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    
    .welcome-content {
      h2 {
        margin: 0 0 8px 0;
        font-size: 24px;
        font-weight: 600;
      }
      
      p {
        margin: 0;
        opacity: 0.9;
      }
    }
    
    .weather-info {
      display: flex;
      align-items: center;
      font-size: 16px;
      
      .el-icon {
        margin-right: 8px;
        font-size: 20px;
      }
    }
  }
  
  .stats-section {
    margin-bottom: 20px;
    
    .stat-card {
      background: #fff;
      border-radius: 8px;
      padding: 20px;
      display: flex;
      align-items: center;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      
      .stat-icon {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16px;
        
        .el-icon {
          font-size: 24px;
          color: #fff;
        }
        
        &.cases {
          background: #409eff;
        }
        
        &.contracts {
          background: #67c23a;
        }
        
        &.clients {
          background: #e6a23c;
        }
        
        &.revenue {
          background: #f56c6c;
        }
      }
      
      .stat-content {
        flex: 1;
        
        .stat-value {
          font-size: 24px;
          font-weight: bold;
          margin-bottom: 4px;
          color: #303133;
        }
        
        .stat-label {
          color: #909399;
          font-size: 14px;
          margin-bottom: 4px;
        }
        
        .stat-change {
          .change-text {
            font-size: 12px;
            color: #67c23a;
          }
        }
      }
    }
  }
  
  .card {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    
    h3 {
      margin: 0 0 16px 0;
      font-size: 16px;
      font-weight: 600;
    }
    
    .card-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 16px;
      
      h3 {
        margin: 0;
      }
    }
  }
  
  .todo-list {
    .todo-item {
      display: flex;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      &.completed {
        .todo-text {
          text-decoration: line-through;
          color: #909399;
        }
      }
      
      .todo-text {
        flex: 1;
        margin-left: 12px;
      }
      
      .delete-btn {
        opacity: 0;
        transition: opacity 0.3s;
      }
      
      &:hover .delete-btn {
        opacity: 1;
      }
    }
  }

  .cloud-legal-features {
    .feature-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
      gap: 20px;
      margin-top: 16px;

      .feature-card {
        padding: 24px;
        border: 1px solid #e4e7ed;
        border-radius: 8px;
        background: #fff;
        cursor: pointer;
        transition: all 0.3s ease;
        position: relative;

        &:hover {
          border-color: #409eff;
          box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
          transform: translateY(-2px);
        }

        .feature-icon {
          font-size: 32px;
          color: #409eff;
          margin-bottom: 12px;
        }

        h4 {
          margin: 0 0 8px 0;
          font-size: 16px;
          font-weight: 600;
          color: #303133;
        }

        p {
          margin: 0 0 12px 0;
          font-size: 14px;
          color: #606266;
          line-height: 1.5;
        }

        .feature-status {
          position: absolute;
          top: 12px;
          right: 12px;
          padding: 4px 8px;
          border-radius: 4px;
          font-size: 12px;
          font-weight: 500;
          background: #67c23a;
          color: #fff;

          &.developing {
            background: #e6a23c;
          }

          &.planning {
            background: #909399;
          }
        }
      }
    }
  }

  .quick-actions {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 12px;

    .action-btn {
      width: 100%;
      height: 60px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      .el-icon {
        margin-bottom: 4px;
        font-size: 18px;
      }
    }
  }
  
  .notification-list {
    .notification-item {
      display: flex;
      align-items: flex-start;
      padding: 12px 0;
      border-bottom: 1px solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .notification-icon {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        background: #409eff;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 12px;
        
        .el-icon {
          color: #fff;
          font-size: 14px;
        }
      }
      
      .notification-content {
        flex: 1;
        
        .notification-title {
          font-size: 14px;
          margin-bottom: 4px;
        }
        
        .notification-time {
          font-size: 12px;
          color: #909399;
        }
      }
    }
  }
}
</style>
